/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-11 17:28:46
 * @LastEditors: LIFM0623 1944099171@qq.com
 * @LastEditTime: 2024-03-12 15:04:21
 * @FilePath: \Scene_Back\src\auth\auth.service.ts
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-02-22 16:46:21
 * @FilePath: \Scene_Back\src\auth\auth.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/user/entities/user.entity';
import { UserService } from 'src/user/user.service';
import { ConfigService } from '@nestjs/config';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class AuthService {
  private readonly secretKey: string;
  constructor(
    private jwtService: JwtService,
    private userService: UserService,
    private configService: ConfigService,
  ) {
    this.secretKey = this.configService.get('SECRET', 'yssyyds');
  }
  async checkToken(token: string): Promise<boolean> {
    try {
      // 验证 JWT
      jwt.verify(token, this.secretKey);
      return true;
    } catch (error) {
      return false
    }
  }

  // 生成 accessToken 和 refreshToken
  generateToken(user: Partial<User>) {
    const payload = { email: user.email };
    return {
      access_token: this.jwtService.sign(payload, {
        expiresIn: '3d',
      }),
      refresh_token: this.jwtService.sign(payload, {
        expiresIn: '5d',
      }),
    };
  }

  refreshToken(refresh_token: string) {
    const secretKey = this.configService.get('SECRET', 'yssyyds');
    try {
      const decodedToken = jwt.verify(refresh_token, secretKey) as {
        email: string;
        iat: any;
        exp: any;
      };
      const user = {
        email: decodedToken.email,
      };
      return this.generateToken(user as Partial<User>);
    } catch (error) {
      throw new BadRequestException('刷新令牌失效');
    }
  }

  async login(user: Partial<User>) {

    return { ...this.generateToken(user) };
  }

  async getUser(user: User) {
    return await this.userService.findOne(user.email);
  }
}
